import java.util.ArrayList;
import java.util.LinkedList;

public class HashTable {
    private final int DEFAULT_TABLE_SIZE = 17;
    private ArrayList<LinkedList<Student>> array = null;

    public ArrayList<LinkedList<Student>> getArray() {
        return array;
    }

    HashTable() {
        // [0-16]大小的Array
        array = new ArrayList<LinkedList<Student>>(DEFAULT_TABLE_SIZE);
        for (int i = 0; i < DEFAULT_TABLE_SIZE; i++) {
            array.add(null);
        }
    }

    /**
     * 新增
     *
     * @param stu
     */
    public void put(Student stu) {
        // 1. 将id hash到[0-16]之间
        int hashValue = Integer.hashCode(stu.id);
        // 2. 将stu放入array中hashValue对应的链表
        int index = hashValue % DEFAULT_TABLE_SIZE;
        LinkedList<Student> linkedList = array.get(index);
        if (linkedList == null) {
            linkedList = new LinkedList<>();
        }
        linkedList.add(stu);
        array.set(index, linkedList);
    }


    /**
     * LRU
     * 查找
     *
     * @param id
     * @return
     */
    public Student get(int id) {
        // 1. 将id hash到[0-16]之间
        int hashValue = Integer.hashCode(id);
        // 2. 将array中hashValue对应的链表中查找出来
        int index = hashValue % DEFAULT_TABLE_SIZE;
        LinkedList<Student> linkedList = array.get(index);
        if (linkedList == null) {
            return null;
        } else {
            for (Student stu : linkedList) {
                if (stu.id == id) {
                    //找到了，把顺序提前
                    linkedList.remove(stu);
                    linkedList.addFirst(stu);
                    return stu;
                }
            }
            return null;
        }
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(int id) {
        int hashValue = Integer.hashCode(id);
        int index = hashValue % DEFAULT_TABLE_SIZE;
        LinkedList<Student> linkedList = array.get(index);
        if (linkedList != null) {
            for (Student stu : linkedList) {
                if (stu.id == id) {
                    linkedList.remove(stu);
                    break;
                }
            }
        }
    }
}